package util.thread.ordertoperform;

import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


/**
 * Object wait() notify() notifyAll()
 *
 * @Author：LiDong
 * @Create：2020/12/2
 * @Version：1.0.0
 */
public class ObjectWaitTest {

    private static final Logger logger = LoggerFactory.getLogger(ObjectWaitTest.class);

    private final Object objectOne = new Object();
    private final Object objectTwo = new Object();

    /**
     * 子线程是否运行完成的标志
     */
    private static boolean ONE_RUN_FLAG = true;
    private static boolean TWO_RUN_FLAG = true;

    class One extends Thread {
        @Override
        public void run() {
            synchronized (objectOne) {
                logger.info("=====》 我是One线程");
                ONE_RUN_FLAG = false;
                objectOne.notify();
                logger.info("=====》 One线程执行完成...");
            }
        }
    }

    class Two extends Thread {
        @Override
        public void run() {
            synchronized (objectOne) {
                try {
                    if (ONE_RUN_FLAG) {
                        logger.info("=====> 线程One没有执行完成，线程二等待中...");
                        objectOne.wait();
                    }
                    synchronized (objectTwo) {
                        logger.info("=====》 我是Two线程");
                        objectTwo.notify();
                        TWO_RUN_FLAG = false;
                        logger.info("=====》Two线程执行完成...");
                    }
                } catch (InterruptedException e) {
                    logger.error(e.getMessage(), e);
                }
            }
        }
    }

    class Three extends Thread {
        @Override
        public void run() {
            synchronized (objectTwo) {
                if (TWO_RUN_FLAG) {
                    try {
                        logger.info("=====> 线程Two没有执行完成，线程三等待中...");
                        objectTwo.wait();
                    } catch (InterruptedException e) {
                        logger.error(e.getMessage(), e);
                    }
                }
                logger.info("=====》 我是Three线程");
                logger.info("=====》 Three线程执行完成...");
            }
        }
    }


    @Test
    public void test1() {
        Thread one = new One();
        one.start();
        Thread two = new Two();
        two.start();
        Thread three = new Three();
        three.start();
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            logger.error(e.getMessage(), e);
        }
        logger.info("=====>三个子线程结束...");

    }

}
